﻿using System;
using System.Windows.Markup;
using System.Windows.Media;

using FirstFloor.Documents.Annotations;
using FirstFloor.Documents.Controls;
using FirstFloor.Documents.Controls.Commands;
using SampleBrowser.Common.Annotations;

namespace SampleBrowser.Common.Commands
{
    /// <summary>
    /// The command that set a hyperlink to the current text selection.
    /// </summary>
    public class HyperlinkCommand
        : SelectionCommand
    {
        /// <summary>
        /// Gets a value indicating whether this command requires text to be selected.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this command requires selected text; otherwise, <c>false</c>.
        /// </value>
        protected override bool RequiresSelectedText
        {
            get { return true; }
        }

        /// <summary>
        /// Defines the method that determines whether the command can execute in its current state.
        /// </summary>
        /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param>
        /// <returns>
        /// true if this command can be executed; otherwise, false.
        /// </returns>
        public override bool CanExecute(object parameter)
        {
            if (base.CanExecute(parameter)){
                var uriString = parameter as string;
                return Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute);
            }
            return false;
        }

        /// <summary>
        /// Implements the actual command execution.
        /// </summary>
        /// <param name="parameter">The parameter.</param>
        protected override void OnExecute(object parameter)
        {
            var uriString = parameter as string;
            Uri targetUri;
            if (Uri.TryCreate(uriString, UriKind.RelativeOrAbsolute, out targetUri)) {
                var service = AnnotationService.GetService(this.Selection.TextContainer);
                if (service != null && service.IsEnabled) {
                    var factory = new HyperlinkFactory();
                    var hyperlink = factory.CreateTextAnnotationForSelection(service);
                    hyperlink.TargetUri = targetUri;
                    this.Selection.Unselect();
                }
            }
        }
    }
}
